<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Terminal - Xshell Alternative</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Menlo', 'Monaco', 'Consolas', monospace;
            background: #1e1e1e;
            color: #ffffff;
            height: 100vh;
            overflow: hidden;
        }

        .app-container {
            display: flex;
            height: 100vh;
            flex-direction: column;
        }

        .header {
            background: #2d2d30;
            padding: 8px 16px;
            border-bottom: 1px solid #3e3e42;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 14px;
            color: #cccccc;
            font-weight: normal;
        }

        .header-controls {
            display: flex;
            gap: 8px;
        }

        .btn {
            background: #0e639c;
            color: white;
            border: none;
            padding: 4px 12px;
            font-size: 12px;
            border-radius: 3px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .btn:hover {
            background: #1177bb;
        }

        .btn.secondary {
            background: #505050;
        }

        .btn.secondary:hover {
            background: #606060;
        }

        .main-content {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            width: 300px;
            background: #252526;
            border-right: 1px solid #3e3e42;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 12px 16px;
            background: #2d2d30;
            border-bottom: 1px solid #3e3e42;
            font-size: 13px;
            font-weight: bold;
        }

        .connection-list {
            flex: 1;
            overflow-y: auto;
        }

        .connection-item {
            padding: 8px 16px;
            border-bottom: 1px solid #3e3e42;
            cursor: pointer;
            transition: background 0.2s;
        }

        .connection-item:hover {
            background: #2a2d2e;
        }

        .connection-item.active {
            background: #094771;
        }

        .ai-panel {
            background: #1e1e1e;
            border-top: 1px solid #3e3e42;
            height: 200px;
            display: flex;
            flex-direction: column;
        }

        .ai-header {
            padding: 8px 16px;
            background: #2d2d30;
            border-bottom: 1px solid #3e3e42;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .ai-content {
            flex: 1;
            padding: 12px;
            overflow-y: auto;
            font-size: 12px;
            line-height: 1.4;
        }

        .ai-input {
            padding: 8px 12px;
            background: #3c3c3c;
            border: none;
            color: white;
            font-family: inherit;
            font-size: 12px;
            outline: none;
        }

        .terminal-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #1e1e1e;
        }

        .terminal-tabs {
            background: #2d2d30;
            border-bottom: 1px solid #3e3e42;
            display: flex;
            overflow-x: auto;
        }

        .terminal-tab {
            padding: 8px 16px;
            background: #252526;
            border-right: 1px solid #3e3e42;
            cursor: pointer;
            font-size: 12px;
            white-space: nowrap;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .terminal-tab.active {
            background: #1e1e1e;
            border-bottom: 2px solid #0e639c;
        }

        .terminal-tab .close-btn {
            background: none;
            border: none;
            color: #cccccc;
            cursor: pointer;
            padding: 0;
            font-size: 14px;
        }

        .terminal-content {
            flex: 1;
            position: relative;
        }

        #terminal {
            width: 100%;
            height: 100%;
            padding: 10px;
        }

        .command-suggestions {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(45, 45, 48, 0.95);
            border-top: 1px solid #3e3e42;
            padding: 8px;
            font-size: 11px;
            transform: translateY(100%);
            transition: transform 0.3s ease;
        }

        .command-suggestions.show {
            transform: translateY(0);
        }

        .suggestion-item {
            padding: 4px 8px;
            margin: 2px 0;
            background: #3c3c3c;
            border-radius: 2px;
            cursor: pointer;
        }

        .suggestion-item:hover {
            background: #0e639c;
        }

        .status-bar {
            background: #007acc;
            color: white;
            padding: 4px 16px;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
        }

        .loading {
            opacity: 0.7;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .ai-thinking {
            animation: pulse 1.5s infinite;
        }

        /* SSH Connection Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: #2d2d30;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #3e3e42;
            border-radius: 8px;
            width: 400px;
            color: #ffffff;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #3e3e42;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 16px;
        }

        .close {
            color: #aaa;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #fff;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-size: 12px;
            color: #cccccc;
        }

        .form-group input {
            width: 100%;
            padding: 8px 12px;
            background: #3c3c3c;
            border: 1px solid #555;
            border-radius: 4px;
            color: white;
            font-family: inherit;
            font-size: 12px;
            box-sizing: border-box;
        }

        .form-group input:focus {
            outline: none;
            border-color: #0e639c;
        }

        .paste-helper {
            background: #3a3a3a;
            border: 1px dashed #555;
            border-radius: 4px;
            padding: 8px;
            margin-bottom: 15px;
            font-size: 11px;
            color: #cccccc;
        }

        .paste-helper .paste-button {
            background: #0e639c;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 10px;
            cursor: pointer;
            margin-left: 8px;
        }

        .paste-helper .paste-button:hover {
            background: #1177bb;
        }

        .paste-formats {
            margin-top: 8px;
            font-size: 10px;
            color: #888;
        }

        .paste-example {
            background: #2a2a2a;
            padding: 4px 6px;
            border-radius: 2px;
            font-family: monospace;
            margin: 2px 0;
        }

        .recent-connection-item {
            background: #2a2a2a;
            padding: 6px 8px;
            margin: 2px 0;
            border-radius: 3px;
            cursor: pointer;
            font-size: 11px;
            font-family: monospace;
            border: 1px solid transparent;
            transition: all 0.2s;
        }

        .recent-connection-item:hover {
            background: #0e639c;
            border-color: #1177bb;
        }

        .form-row {
            display: flex;
            gap: 10px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #3e3e42;
        }

        .btn-cancel {
            background: #6c757d;
        }

        .btn-cancel:hover {
            background: #5a6268;
        }

        .connection-status {
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 10px;
            margin-left: 8px;
        }

        .status-connected {
            background: #28a745;
            color: white;
        }

        .status-connecting {
            background: #ffc107;
            color: black;
        }

        .status-disconnected {
            background: #dc3545;
            color: white;
        }

        .connection-item .connection-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 4px;
        }

        .connection-info {
            font-size: 10px;
            color: #888;
        }

        .connection-controls {
            display: flex;
            gap: 4px;
        }

        .btn-small {
            padding: 2px 6px;
            font-size: 10px;
            border-radius: 2px;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <h1>🤖 AI Terminal - Intelligent Xshell Alternative</h1>
            <div class="header-controls">
                <button class="btn" onclick="showSSHModal()">+ SSH Connection</button>
                <button class="btn secondary" onclick="toggleAI()">AI Assistant</button>
                <button class="btn secondary" onclick="openSettings()">Settings</button>
            </div>
        </div>

        <div class="main-content">
            <div class="sidebar">
                <div class="sidebar-header">Connections</div>
                <div class="connection-list" id="connectionList">
                    <div class="connection-item active" onclick="selectConnection('local')" data-connection-id="local">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div>💻 Local Terminal</div>
                                <small style="color: #cccccc; font-size: 11px;">localhost</small>
                            </div>
                            <span class="connection-status status-connected">Connected</span>
                        </div>
                    </div>
                </div>
                
                <div class="ai-panel" id="aiPanel">
                    <div class="ai-header">
                        <span>🤖 AI Assistant</span>
                        <button class="btn" style="font-size: 10px; padding: 2px 6px;" onclick="clearAIChat()">Clear</button>
                    </div>
                    <div class="ai-content" id="aiContent">
                        <div style="color: #6c9bd1;">AI: Hello! I'm your terminal AI assistant. I can help you with commands, explain outputs, and troubleshoot issues. What would you like to know?</div>
                    </div>
                    <input type="text" class="ai-input" id="aiInput" placeholder="Ask AI anything about your terminal..." onkeypress="handleAIInput(event)">
                </div>
            </div>

            <div class="terminal-container">
                <div class="terminal-tabs">
                    <div class="terminal-tab active" data-session="main">
                        <span>Terminal 1</span>
                        <button class="close-btn" onclick="closeTab(this)">&times;</button>
                    </div>
                    <button class="btn" style="margin: 4px; font-size: 11px; padding: 4px 8px;" onclick="newTab()">+</button>
                </div>
                
                <div class="terminal-content">
                    <div id="terminal"></div>
                    
                    <div class="command-suggestions" id="suggestions">
                        <div style="margin-bottom: 4px; font-weight: bold;">💡 AI Suggestions:</div>
                        <div class="suggestion-item" onclick="applySuggestion(this)">ls -la</div>
                        <div class="suggestion-item" onclick="applySuggestion(this)">pwd</div>
                        <div class="suggestion-item" onclick="applySuggestion(this)">cd ~</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="status-bar">
            <span id="statusLeft">Ready - AI Assistant Active</span>
            <span id="statusRight">Local Session | UTF-8</span>
        </div>
    </div>

    <!-- SSH Connection Modal -->
    <div id="sshModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>🔗 New SSH Connection</h3>
                <span class="close" onclick="closeSSHModal()">&times;</span>
            </div>
            
            <form id="sshForm" onsubmit="createSSHConnection(event)">
                <div class="paste-helper">
                    <span>📋 Quick Setup:</span>
                    <button type="button" class="paste-button" onclick="pasteConnectionInfo()">Paste Connection Info</button>
                    <button type="button" class="paste-button" onclick="showRecentConnections()" style="margin-left: 4px;">Recent</button>
                    <div class="paste-formats">
                        Supports formats:
                        <div class="paste-example">user@hostname:port</div>
                        <div class="paste-example">ssh://user:password@hostname:port</div>
                        <div class="paste-example">hostname:port user password</div>
                        <div class="paste-example">39.98.71.228:122<br>username</div>
                    </div>
                    <div id="recentConnections" style="display: none; margin-top: 8px;"></div>
                </div>
                
                <div class="form-group">
                    <label for="connectionName">Connection Name</label>
                    <input type="text" id="connectionName" placeholder="My Server" required>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="hostname">Hostname/IP</label>
                        <input type="text" id="hostname" placeholder="192.168.1.100 or user@server.com:22" required
                               title="You can paste: user@hostname:port, ssh://user@host:port, or just hostname">
                    </div>
                    <div class="form-group" style="flex: 0 0 80px;">
                        <label for="port">Port</label>
                        <input type="number" id="port" value="22" required min="1" max="65535">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" id="username" placeholder="root" required>
                </div>
                
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" placeholder="Enter password" required>
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="saveConnection" checked>
                        Save this connection
                    </label>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-cancel" onclick="closeSSHModal()">Cancel</button>
                    <button type="submit" class="btn">Connect</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Load xterm.js from local files for offline support -->
    <script src="/static/js/xterm.min.js"></script>
    <script src="/static/js/xterm-addon-fit.min.js"></script>
    <!-- Basic xterm.js CSS styling -->
    <style>
        .xterm {
            font-feature-settings: "liga" 0;
            position: relative;
            user-select: none;
            -ms-user-select: none;
            -webkit-user-select: none;
        }
        .xterm.focus {
            outline: none;
        }
        .xterm .xterm-helpers {
            position: absolute;
            top: 0;
            z-index: 5;
        }
        .xterm .xterm-helper-textarea {
            position: absolute;
            opacity: 0;
            left: -9999em;
            top: 0;
            width: 0;
            height: 0;
            z-index: -5;
            white-space: nowrap;
            overflow: hidden;
            resize: none;
        }
        .xterm .composition-view {
            background: #000;
            color: #FFF;
            display: none;
            position: absolute;
            white-space: nowrap;
            z-index: 1;
        }
        .xterm .composition-view.active {
            display: block;
        }
        .xterm .xterm-viewport {
            background-color: #000;
            overflow-y: scroll;
            cursor: default;
            position: absolute;
            right: 0;
            left: 0;
            top: 0;
            bottom: 0;
        }
        .xterm .xterm-screen {
            position: relative;
        }
        .xterm .xterm-screen canvas {
            position: absolute;
            left: 0;
            top: 0;
        }
        .xterm .xterm-scroll-area {
            visibility: hidden;
        }
        .xterm-char-measure-element {
            display: inline-block;
            visibility: hidden;
            position: absolute;
            top: 0;
            left: -9999em;
            line-height: normal;
        }
        .xterm {
            cursor: text;
        }
        .xterm.enable-mouse-events {
            cursor: default;
        }
        .xterm.xterm-cursor-pointer {
            cursor: pointer;
        }
        .xterm.column-select.focus {
            cursor: crosshair;
        }
        .xterm .xterm-accessibility,
        .xterm .xterm-message {
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            z-index: 10;
            color: transparent;
        }
        .xterm .live-region {
            position: absolute;
            left: -9999px;
            width: 1px;
            height: 1px;
            overflow: hidden;
        }
        .xterm-dim {
            opacity: 0.5;
        }
        .xterm-underline {
            text-decoration: underline;
        }
    </style>

    <script>
        // Global variables
        let terminal;
        let fitAddon;
        let currentCommand = '';
        let commandHistory = [];
        let historyIndex = -1;
        let aiAssistantEnabled = true;
        let webSocket = null;
        let activeConnections = new Map();
        let currentConnectionId = 'local';

        // Initialize the application
        function initApp() {
            initTerminal();
            initWebSocket();
            setupEventListeners();
            updateStatus('Initializing AI Terminal...');
            
            // Simulate connection establishment
            setTimeout(() => {
                updateStatus('Connected - AI Assistant Ready');
                terminal.writeln('\x1b[32mWelcome to AI Terminal! 🤖\x1b[0m');
                terminal.writeln('\x1b[36mType "ai help" for AI assistant commands\x1b[0m');
                terminal.writeln('');
                showPrompt();
            }, 1000);
        }

        // Initialize xterm.js terminal
        function initTerminal() {
            terminal = new Terminal({
                cursorBlink: true,
                theme: {
                    background: '#1e1e1e',
                    foreground: '#ffffff',
                    cursor: '#ffffff',
                    selection: '#264f78'
                },
                fontSize: 14,
                fontFamily: 'Menlo, Monaco, Consolas, monospace',
                rows: 24,
                cols: 80,
                allowTransparency: false,
                allowProposedApi: true
            });

            fitAddon = new FitAddon.FitAddon();
            terminal.loadAddon(fitAddon);
            
            terminal.open(document.getElementById('terminal'));
            fitAddon.fit();

            // Handle terminal input with better SSH support
            terminal.onData(data => {
                handleTerminalInput(data);
            });

            // Handle window resize
            window.addEventListener('resize', () => {
                fitAddon.fit();
                
                // Send resize info to server for SSH sessions
                if (currentConnectionId !== 'local' && webSocket && webSocket.readyState === WebSocket.OPEN) {
                    const dimensions = fitAddon.proposeDimensions();
                    if (dimensions) {
                        webSocket.send(JSON.stringify({
                            type: 'terminal_resize',
                            session_id: currentConnectionId,
                            cols: dimensions.cols,
                            rows: dimensions.rows
                        }));
                    }
                }
            });
            
            // Ensure terminal is focused
            terminal.focus();
            
            // Add click handler to refocus terminal
            document.getElementById('terminal').addEventListener('click', () => {
                terminal.focus();
                console.log('Terminal clicked and focused');
            });
        }

        // Initialize WebSocket connection to Python backend
        function initWebSocket() {
            const clientId = 'client_' + Date.now();
            const wsUrl = `ws://localhost:8001/ws/${clientId}`;
            
            console.log(`Attempting to connect to: ${wsUrl}`);
            
            try {
                webSocket = new WebSocket(wsUrl);
                
                webSocket.onopen = () => {
                    console.log('✅ Connected to Python backend via WebSocket');
                    updateStatus('Connected to AI Terminal Server');
                    
                    // Send a test message to verify connection
                    webSocket.send(JSON.stringify({
                        type: 'test_connection',
                        client_id: clientId,
                        timestamp: new Date().toISOString()
                    }));
                };
                
                webSocket.onmessage = (event) => {
                    console.log('📨 Received WebSocket message:', event.data);
                    try {
                        const data = JSON.parse(event.data);
                        handleWebSocketMessage(data);
                    } catch (error) {
                        console.error('❌ Error parsing WebSocket message:', error, 'Raw data:', event.data);
                    }
                };
                
                webSocket.onclose = (event) => {
                    console.log('🔌 WebSocket connection closed:', event.code, event.reason);
                    updateStatus('Disconnected from server');
                    // Attempt reconnection after 3 seconds
                    setTimeout(() => {
                        console.log('🔄 Attempting to reconnect...');
                        initWebSocket();
                    }, 3000);
                };
                
                webSocket.onerror = (error) => {
                    console.error('❌ WebSocket error:', error);
                    updateStatus('Connection error - retrying...');
                };
                
            } catch (error) {
                console.log('❌ WebSocket connection failed, running in demo mode:', error);
                updateStatus('Demo mode - Python backend not available');
            }
        }
        
        // Handle WebSocket messages from Python backend
        function handleWebSocketMessage(data) {
            console.log('🔄 Processing message type:', data.type, 'Data:', data);
            
            switch(data.type) {
                case 'terminal_output':
                    console.log('📟 Terminal output for session:', data.session_id, 'Current:', currentConnectionId);
                    console.log('📟 Output data:', JSON.stringify(data.data));
                    if (data.session_id === currentConnectionId) {
                        terminal.write(data.data);
                        console.log('✅ Terminal output written to current session');
                    } else {
                        console.log('⚠️ Terminal output ignored - session mismatch');
                    }
                    break;
                    
                case 'ssh_connected':
                    console.log('🔗 SSH Connected:', data);
                    handleSSHConnected(data);
                    break;
                    
                case 'ssh_error':
                    console.log('❌ SSH Error:', data);
                    handleSSHError(data);
                    break;
                    
                case 'ssh_disconnected':
                    console.log('🔌 SSH Disconnected:', data);
                    handleSSHDisconnected(data);
                    break;
                    
                case 'ai_command_response':
                    console.log('🤖 AI Command Response:', data);
                    handleAICommandResponse(data);
                    break;
                    
                case 'ai_chat_stream_start':
                    console.log('🌊 AI Chat Stream Start:', data);
                    handleAIChatStreamStart(data);
                    break;
                    
                case 'ai_chat_stream_chunk':
                    console.log('📝 AI Chat Stream Chunk:', data);
                    handleAIChatStreamChunk(data);
                    break;
                    
                case 'ai_chat_response':
                    console.log('💬 AI Chat Response:', data);
                    handleAIChatResponse(data);
                    break;
                    
                case 'suggestions_response':
                    console.log('💡 Suggestions Response:', data);
                    handleSuggestionsResponse(data);
                    break;
                    
                case 'ai_error':
                    console.log('❌ AI Error:', data);
                    handleAIError(data);
                    break;
                    
                case 'test_connection':
                    console.log('✅ Connection test successful');
                    break;
                    
                default:
                    console.log('❓ Unknown message type:', data.type, 'Full data:', data);
            }
        }

        // Setup event listeners
        function setupEventListeners() {
            document.addEventListener('keydown', (e) => {
                if (e.ctrlKey && e.key === 't') {
                    e.preventDefault();
                    newTab();
                }
                if (e.ctrlKey && e.key === 'w') {
                    e.preventDefault();
                    closeCurrentTab();
                }
            });
        }

        // Handle terminal input
        function handleTerminalInput(data) {
            const code = data.charCodeAt(0);
            const isSSH = currentConnectionId !== 'local';
            
            console.log(`Terminal input received: ${JSON.stringify(data)}, code: ${code}, isSSH: ${isSSH}, currentConnection: ${currentConnectionId}`);
            
            // For SSH connections, send all input directly to server without local echo
            if (isSSH && webSocket && webSocket.readyState === WebSocket.OPEN) {
                console.log(`Sending SSH input to server: ${JSON.stringify(data)}`);
                webSocket.send(JSON.stringify({
                    type: 'terminal_input',
                    session_id: currentConnectionId,
                    input: data
                }));
                return;
            }
            
            // Handle local terminal input
            if (code === 13) { // Enter key
                terminal.writeln('');
                executeCommand(currentCommand.trim());
                currentCommand = '';
                return;
            }
            
            if (code === 127) { // Backspace
                if (currentCommand.length > 0) {
                    currentCommand = currentCommand.slice(0, -1);
                    terminal.write('\b \b');
                }
                return;
            }
            
            if (code === 9) { // Tab key
                handleTabCompletion();
                return;
            }
            
            if (code >= 32) { // Printable characters
                currentCommand += data;
                terminal.write(data);
                
                // Show AI suggestions for local commands
                if (currentCommand.length > 2) {
                    showCommandSuggestions(currentCommand);
                }
            }
        }

        // Execute command
        function executeCommand(command) {
            if (!command) {
                showPrompt();
                return;
            }

            // Add to history
            commandHistory.push(command);
            historyIndex = commandHistory.length;

            // Handle special AI commands
            if (command.startsWith('ai ')) {
                handleAICommand(command.substring(3));
                return;
            }

            // Simulate command execution
            simulateCommandExecution(command);
        }

        // Handle AI commands
        function handleAICommand(aiCommand) {
            if (aiCommand === 'help') {
                terminal.writeln('\x1b[36mAI Assistant Commands:\x1b[0m');
                terminal.writeln('  ai help          - Show this help');
                terminal.writeln('  ai explain <cmd> - Explain a command');
                terminal.writeln('  ai suggest       - Get command suggestions');
                terminal.writeln('  ai fix           - Help fix the last error');
                terminal.writeln('  ai generate <natural language> - Generate command from description');
                terminal.writeln('');
            } else if (aiCommand.startsWith('explain ')) {
                const cmd = aiCommand.substring(8);
                explainCommand(cmd);
            } else if (aiCommand === 'suggest') {
                requestAISuggestions();
            } else if (aiCommand.startsWith('generate ')) {
                const query = aiCommand.substring(9);
                generateAICommand(query);
            } else {
                askAI(aiCommand);
            }
            showPrompt();
        }
        
        // Generate AI command from natural language
        function generateAICommand(query) {
            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                webSocket.send(JSON.stringify({
                    type: 'ai_command',
                    query: query,
                    command_type: 'linux',
                    context: {
                        current_directory: '/home/user',
                        connection_id: currentConnectionId
                    }
                }));
                
                terminal.writeln('\x1b[36m🤖 Generating command with AI...\x1b[0m');
            } else {
                terminal.writeln('\x1b[31mAI service not available\x1b[0m');
            }
        }
        
        // Request AI suggestions
        function requestAISuggestions() {
            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                webSocket.send(JSON.stringify({
                    type: 'get_suggestions',
                    connection_id: currentConnectionId,
                    context: {
                        current_time: new Date().toISOString(),
                        connection_type: currentConnectionId === 'local' ? 'local' : 'ssh'
                    }
                }));
                
                terminal.writeln('\x1b[36m🤖 Getting AI suggestions...\x1b[0m');
            } else {
                showAISuggestions();
            }
        }

        // Simulate command execution
        function simulateCommandExecution(command) {
            updateStatus('Executing: ' + command);
            
            setTimeout(() => {
                const parts = command.split(' ');
                const cmd = parts[0];
                
                switch(cmd) {
                    case 'ls':
                        terminal.writeln('total 8');
                        terminal.writeln('drwxr-xr-x  3 user staff  96 Dec 15 10:30 .');
                        terminal.writeln('drwxr-xr-x  5 user staff 160 Dec 15 10:25 ..');
                        terminal.writeln('-rw-r--r--  1 user staff 1234 Dec 15 10:30 file.txt');
                        terminal.writeln('-rwxr-xr-x  1 user staff 5678 Dec 15 10:29 script.sh');
                        break;
                    case 'pwd':
                        terminal.writeln('/Users/user/workspace');
                        break;
                    case 'date':
                        terminal.writeln(new Date().toString());
                        break;
                    case 'whoami':
                        terminal.writeln('user');
                        break;
                    case 'clear':
                        terminal.clear();
                        break;
                    default:
                        if (command.includes('error') || command.includes('fail')) {
                            terminal.writeln('\x1b[31mError: Command failed\x1b[0m');
                            suggestAIHelp();
                        } else {
                            terminal.writeln(`Command output for: ${command}`);
                        }
                }
                
                terminal.writeln('');
                updateStatus('Ready');
                showPrompt();
            }, 500);
        }

        // Show command prompt
        function showPrompt() {
            terminal.write('\x1b[32muser@ai-terminal\x1b[0m:\x1b[34m~/workspace\x1b[0m$ ');
        }

        // Show command suggestions
        function showCommandSuggestions(input) {
            const suggestions = document.getElementById('suggestions');
            const items = suggestions.querySelectorAll('.suggestion-item');
            
            // Clear existing suggestions
            items.forEach(item => item.remove());
            
            // Generate AI-powered suggestions
            const commonCommands = ['ls', 'cd', 'pwd', 'cat', 'grep', 'find', 'ps', 'top', 'chmod', 'chown'];
            const matches = commonCommands.filter(cmd => cmd.startsWith(input.split(' ')[0]));
            
            if (matches.length > 0) {
                matches.slice(0, 3).forEach(match => {
                    const item = document.createElement('div');
                    item.className = 'suggestion-item';
                    item.textContent = match;
                    item.onclick = () => applySuggestion(item);
                    suggestions.appendChild(item);
                });
                suggestions.classList.add('show');
                
                setTimeout(() => {
                    suggestions.classList.remove('show');
                }, 3000);
            }
        }

        // Apply suggestion
        function applySuggestion(element) {
            const suggestion = element.textContent;
            currentCommand = suggestion;
            terminal.write('\r\x1b[K'); // Clear current line
            showPrompt();
            terminal.write(suggestion);
            document.getElementById('suggestions').classList.remove('show');
        }

        // Handle tab completion
        function handleTabCompletion() {
            const parts = currentCommand.split(' ');
            const lastPart = parts[parts.length - 1];
            
            // Simple tab completion simulation
            const completions = ['file.txt', 'script.sh', 'directory/', 'another_file.log'];
            const matches = completions.filter(item => item.startsWith(lastPart));
            
            if (matches.length === 1) {
                const completion = matches[0].substring(lastPart.length);
                currentCommand += completion;
                terminal.write(completion);
            }
        }

        // AI Functions
        function askAI(question) {
            addAIMessage('User: ' + question, 'user');
            
            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                webSocket.send(JSON.stringify({
                    type: 'ai_chat',
                    message: question,
                    context: {
                        connection_id: currentConnectionId,
                        current_time: new Date().toISOString()
                    }
                }));
            } else {
                // Fallback response
                setTimeout(() => {
                    const responses = [
                        "I can help you with that! Try using 'ai generate <description>' to create commands.",
                        "That's a great question! Use 'ai generate find files by name' to get the appropriate command.",
                        "I'd recommend using 'ai explain command_name' for detailed information about commands.",
                        "For file operations, try 'ai generate list files with details' to get the right command.",
                        "That error usually indicates a permission issue. Try 'ai generate check file permissions'."
                    ];
                    
                    const response = responses[Math.floor(Math.random() * responses.length)];
                    addAIMessage('AI: ' + response, 'ai');
                }, 1000);
            }
        }

        function explainCommand(command) {
            terminal.writeln('\x1b[36m🤖 AI Explanation:\x1b[0m');
            
            const explanations = {
                'ls': 'Lists directory contents. Use -l for detailed format, -a to show hidden files.',
                'cd': 'Changes the current directory. Use "cd .." to go up one level.',
                'pwd': 'Prints the current working directory path.',
                'grep': 'Searches for patterns in text. Very powerful for finding specific content.',
                'find': 'Searches for files and directories based on various criteria.',
                'chmod': 'Changes file permissions. Use carefully as it affects security.',
                'ps': 'Shows running processes. Add "aux" for detailed process information.'
            };
            
            const explanation = explanations[command] || `Command "${command}" - I'd recommend checking the manual with "man ${command}"`;
            terminal.writeln(explanation);
            terminal.writeln('');
        }

        function showAISuggestions() {
            terminal.writeln('\x1b[36m🤖 AI Suggestions based on current context:\x1b[0m');
            terminal.writeln('  • ls -la          - See detailed file listing');
            terminal.writeln('  • git status      - Check git repository status');
            terminal.writeln('  • ps aux | grep   - Find specific running processes');
            terminal.writeln('  • tail -f log.txt - Monitor log file in real-time');
            terminal.writeln('');
        }

        function suggestAIHelp() {
            setTimeout(() => {
                terminal.writeln('\x1b[33m💡 Tip: Type "ai fix" to get help with this error\x1b[0m');
            }, 100);
        }

        function addAIMessage(message, sender) {
            const aiContent = document.getElementById('aiContent');
            const messageDiv = document.createElement('div');
            messageDiv.style.margin = '4px 0';
            messageDiv.style.color = sender === 'ai' ? '#6c9bd1' : '#ffffff';
            messageDiv.textContent = message;
            aiContent.appendChild(messageDiv);
            aiContent.scrollTop = aiContent.scrollHeight;
        }

        function handleAIInput(event) {
            if (event.key === 'Enter') {
                const input = event.target.value.trim();
                if (input) {
                    askAI(input);
                    event.target.value = '';
                }
            }
        }

        function clearAIChat() {
            const aiContent = document.getElementById('aiContent');
            aiContent.innerHTML = '<div style="color: #6c9bd1;">AI: Chat cleared. How can I help you?</div>';
        }

        // UI Functions
        function showSSHModal() {
            document.getElementById('sshModal').style.display = 'block';
            document.getElementById('connectionName').focus();
        }

        function closeSSHModal() {
            document.getElementById('sshModal').style.display = 'none';
            document.getElementById('sshForm').reset();
            document.getElementById('port').value = '22'; // Reset default port
        }

        // Parse and fill connection information from various formats
        async function pasteConnectionInfo() {
            try {
                const clipboardText = await navigator.clipboard.readText();
                const parsed = parseConnectionString(clipboardText.trim());
                
                if (parsed) {
                    // Fill form fields
                    if (parsed.hostname) {
                        document.getElementById('hostname').value = parsed.hostname;
                        // Auto-generate connection name if not set
                        if (!document.getElementById('connectionName').value) {
                            document.getElementById('connectionName').value = parsed.hostname;
                        }
                    }
                    if (parsed.port) document.getElementById('port').value = parsed.port;
                    if (parsed.username) document.getElementById('username').value = parsed.username;
                    if (parsed.password) document.getElementById('password').value = parsed.password;
                    
                    // Show success feedback
                    showPasteSuccess(parsed);
                } else {
                    showPasteError('Could not parse connection information. Please check the format.');
                }
            } catch (error) {
                if (error.name === 'NotAllowedError') {
                    showPasteError('Clipboard access denied. Please paste manually or allow clipboard permissions.');
                } else {
                    console.error('Paste error:', error);
                    showPasteError('Error accessing clipboard: ' + error.message);
                }
            }
        }

        // Parse connection string in various formats
        function parseConnectionString(connectionString) {
            const result = {
                hostname: '',
                port: 22,
                username: '',
                password: ''
            };
            
            // Remove whitespace and split by newlines
            const lines = connectionString.trim().split(/\r?\n/).map(line => line.trim()).filter(line => line);
            
            // If multiple lines, try to parse them as separate components
            if (lines.length > 1) {
                // First line: hostname:port or user@hostname:port
                const firstLine = lines[0];
                const secondLine = lines[1];
                
                // Parse first line
                let match = firstLine.match(/^([^@]+)@([^:]+):?(\d+)?$/);
                if (match) {
                    // user@hostname:port format
                    result.username = match[1];
                    result.hostname = match[2];
                    result.port = match[3] ? parseInt(match[3]) : 22;
                } else {
                    // hostname:port format
                    match = firstLine.match(/^([^:]+):?(\d+)?$/);
                    if (match) {
                        result.hostname = match[1];
                        result.port = match[2] ? parseInt(match[2]) : 22;
                    }
                }
                
                // Second line: username or password
                if (!result.username && secondLine) {
                    result.username = secondLine;
                }
                
                // Third line: password (if exists)
                if (lines.length > 2 && lines[2]) {
                    result.password = lines[2];
                }
                
                if (result.hostname) {
                    return result;
                }
            }
            
            // Single line parsing (existing logic)
            const singleLine = lines[0] || connectionString.trim();
            
            // Format 1: ssh://user:password@hostname:port
            let match = singleLine.match(/^ssh:\/\/([^:]+):([^@]+)@([^:]+):?(\d+)?$/);
            if (match) {
                result.username = match[1];
                result.password = match[2];
                result.hostname = match[3];
                result.port = match[4] ? parseInt(match[4]) : 22;
                return result;
            }
            
            // Format 2: ssh://user@hostname:port
            match = singleLine.match(/^ssh:\/\/([^@]+)@([^:]+):?(\d+)?$/);
            if (match) {
                result.username = match[1];
                result.hostname = match[2];
                result.port = match[3] ? parseInt(match[3]) : 22;
                return result;
            }
            
            // Format 3: user@hostname:port
            match = singleLine.match(/^([^@]+)@([^:]+):?(\d+)?$/);
            if (match) {
                result.username = match[1];
                result.hostname = match[2];
                result.port = match[3] ? parseInt(match[3]) : 22;
                return result;
            }
            
            // Format 4: hostname:port user password (space separated)
            const parts = singleLine.split(/\s+/);
            if (parts.length >= 3) {
                const hostPort = parts[0].split(':');
                result.hostname = hostPort[0];
                result.port = hostPort[1] ? parseInt(hostPort[1]) : 22;
                result.username = parts[1];
                result.password = parts.slice(2).join(' '); // In case password has spaces
                return result;
            }
            
            // Format 5: hostname:port user (no password)
            if (parts.length === 2) {
                const hostPort = parts[0].split(':');
                result.hostname = hostPort[0];
                result.port = hostPort[1] ? parseInt(hostPort[1]) : 22;
                result.username = parts[1];
                return result;
            }
            
            // Format 6: hostname:port (no user)
            match = singleLine.match(/^([^:]+):?(\d+)?$/);
            if (match) {
                result.hostname = match[1];
                result.port = match[2] ? parseInt(match[2]) : 22;
                return result;
            }
            
            // Format 7: just hostname
            if (singleLine && !singleLine.includes(' ') && singleLine.length > 0) {
                result.hostname = singleLine;
                return result;
            }
            
            return null;
        }

        function showPasteSuccess(parsed) {
            const helper = document.querySelector('.paste-helper');
            const originalContent = helper.innerHTML;
            
            helper.innerHTML = `
                <span style="color: #28a745;">✓ Parsed successfully!</span>
                <span style="font-size: 10px; color: #888; margin-left: 8px;">
                    ${parsed.username ? parsed.username + '@' : ''}${parsed.hostname}${parsed.port !== 22 ? ':' + parsed.port : ''}
                </span>
            `;
            
            setTimeout(() => {
                helper.innerHTML = originalContent;
            }, 3000);
        }

        function showPasteError(message) {
            const helper = document.querySelector('.paste-helper');
            const originalContent = helper.innerHTML;
            
            helper.innerHTML = `
                <span style="color: #dc3545;">⚠ ${message}</span>
            `;
            
            setTimeout(() => {
                helper.innerHTML = originalContent;
            }, 5000);
        }

        // Show/hide recent connections
        function showRecentConnections() {
            const recentDiv = document.getElementById('recentConnections');
            const recentConnections = loadRecentConnections();
            
            if (recentConnections.length === 0) {
                recentDiv.innerHTML = '<div style="color: #888; font-size: 10px;">No recent connections</div>';
                recentDiv.style.display = 'block';
                setTimeout(() => { recentDiv.style.display = 'none'; }, 2000);
                return;
            }
            
            if (recentDiv.style.display === 'none' || !recentDiv.style.display) {
                let html = '<div style="font-size: 10px; color: #888; margin-bottom: 4px;">Recent connections:</div>';
                
                recentConnections.forEach((conn, index) => {
                    html += `
                        <div class="recent-connection-item" onclick="fillRecentConnection(${index})">
                            🔗 ${conn.name} (${conn.username}@${conn.hostname}:${conn.port})
                        </div>
                    `;
                });
                
                recentDiv.innerHTML = html;
                recentDiv.style.display = 'block';
            } else {
                recentDiv.style.display = 'none';
            }
        }

        // Fill form with recent connection data
        function fillRecentConnection(index) {
            const recentConnections = loadRecentConnections();
            const conn = recentConnections[index];
            
            if (conn) {
                document.getElementById('connectionName').value = conn.name;
                document.getElementById('hostname').value = conn.hostname;
                document.getElementById('port').value = conn.port;
                document.getElementById('username').value = conn.username;
                // Password field remains empty for security
                document.getElementById('password').focus();
                
                // Hide recent connections
                document.getElementById('recentConnections').style.display = 'none';
                
                showPasteSuccess(conn);
            }
        }

        // Test parsing function (for debugging)
        function testConnectionParsing() {
            const testCases = [
                '39.98.71.228:122\nasdfasdf',
                '192.168.1.100:22\nroot\nmypassword',
                'user@server.com:2222',
                'ssh://admin:pass@host.com:22',
                '10.0.0.1:3333 ubuntu mypass',
                'server.com'
            ];
            
            console.log('Testing connection string parsing:');
            testCases.forEach(test => {
                const result = parseConnectionString(test);
                console.log(`Input: ${JSON.stringify(test)}`);
                console.log(`Output:`, result);
                console.log('---');
            });
        }

        function createSSHConnection(event) {
            event.preventDefault();
            
            const formData = {
                name: document.getElementById('connectionName').value,
                hostname: document.getElementById('hostname').value,
                port: parseInt(document.getElementById('port').value),
                username: document.getElementById('username').value,
                password: document.getElementById('password').value,
                saveConnection: document.getElementById('saveConnection').checked
            };
            
            // Validate form data
            if (!formData.name || !formData.hostname || !formData.username || !formData.password) {
                alert('Please fill in all required fields');
                return;
            }
            
            // Save to localStorage if requested (without password for security)
            if (formData.saveConnection) {
                saveConnectionToHistory({
                    name: formData.name,
                    hostname: formData.hostname,
                    port: formData.port,
                    username: formData.username
                    // Password is NOT saved for security
                });
            }
            
            // Create connection ID
            const connectionId = 'ssh_' + Date.now();
            
            // Add to connections list
            addConnectionToList(connectionId, formData);
            
            // Attempt SSH connection
            connectSSH(connectionId, formData);
            
            // Close modal
            closeSSHModal();
        }

        // Save connection info to localStorage (without password)
        function saveConnectionToHistory(connectionInfo) {
            try {
                let savedConnections = JSON.parse(localStorage.getItem('sshConnections') || '[]');
                
                // Remove duplicate if exists
                savedConnections = savedConnections.filter(conn => 
                    !(conn.hostname === connectionInfo.hostname && conn.username === connectionInfo.username)
                );
                
                // Add to beginning of array
                savedConnections.unshift(connectionInfo);
                
                // Keep only last 10 connections
                savedConnections = savedConnections.slice(0, 10);
                
                localStorage.setItem('sshConnections', JSON.stringify(savedConnections));
            } catch (error) {
                console.error('Failed to save connection:', error);
            }
        }

        // Load and show recent connections
        function loadRecentConnections() {
            try {
                const savedConnections = JSON.parse(localStorage.getItem('sshConnections') || '[]');
                return savedConnections;
            } catch (error) {
                console.error('Failed to load connections:', error);
                return [];
            }
        }

        function addConnectionToList(connectionId, connectionData) {
            const connectionList = document.getElementById('connectionList');
            const newItem = document.createElement('div');
            newItem.className = 'connection-item';
            newItem.setAttribute('data-connection-id', connectionId);
            newItem.onclick = () => selectConnection(connectionId);
            
            newItem.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <div>🔗 ${connectionData.name}</div>
                        <small style="color: #cccccc; font-size: 11px;">${connectionData.username}@${connectionData.hostname}:${connectionData.port}</small>
                    </div>
                    <span class="connection-status status-connecting">Connecting...</span>
                </div>
                <div class="connection-actions">
                    <div class="connection-info">SSH Connection</div>
                    <div class="connection-controls">
                        <button class="btn btn-small" onclick="event.stopPropagation(); reconnectSSH('${connectionId}')">Reconnect</button>
                        <button class="btn btn-small btn-cancel" onclick="event.stopPropagation(); removeConnection('${connectionId}')">Remove</button>
                    </div>
                </div>
            `;
            
            connectionList.appendChild(newItem);
            
            // Store connection data
            activeConnections.set(connectionId, {
                ...connectionData,
                status: 'connecting',
                element: newItem
            });
        }

        function connectSSH(connectionId, connectionData) {
            updateStatus(`Connecting to ${connectionData.hostname}...`);
            
            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                // Send SSH connection request to Python server
                webSocket.send(JSON.stringify({
                    type: 'ssh_connect',
                    connection: {
                        name: connectionData.name,
                        hostname: connectionData.hostname,
                        port: connectionData.port,
                        username: connectionData.username,
                        password: connectionData.password,
                        enterprise: connectionData.enterprise || 'Default'
                    }
                }));
            } else {
                // Simulate SSH connection for demo
                setTimeout(() => {
                    handleSSHConnected({
                        session_id: connectionId,
                        success: true,
                        message: 'SSH connection established (simulated)'
                    });
                }, 2000);
            }
        }

        // Handle SSH connection established
        function handleSSHConnected(data) {
            console.log(`🔗 SSH Connected with session_id: ${data.session_id}`);
            
            // Find connection by temporary ID and update it with the real session ID
            let connection = null;
            for (let [tempId, conn] of activeConnections) {
                if (conn.status === 'connecting' && !conn.session_id) {
                    connection = conn;
                    connection.session_id = data.session_id;
                    // Remove old entry and add with new session ID
                    activeConnections.delete(tempId);
                    activeConnections.set(data.session_id, connection);
                    // Update the data-connection-id attribute
                    connection.element.setAttribute('data-connection-id', data.session_id);
                    break;
                }
            }
            
            if (connection) {
                connection.status = data.success ? 'connected' : 'disconnected';
                
                const statusElement = connection.element.querySelector('.connection-status');
                statusElement.textContent = data.success ? 'Connected' : 'Failed';
                statusElement.className = `connection-status ${data.success ? 'status-connected' : 'status-disconnected'}`;
                
                if (data.success) {
                    updateStatus(`Connected to ${connection.hostname}`);
                    
                    // Automatically switch to this connection using the real session ID
                    selectConnection(data.session_id);
                    
                    // Clear terminal and show connection message
                    terminal.clear();
                    terminal.writeln(`\x1b[32mSSH connection established to ${connection.hostname}\x1b[0m`);
                    terminal.writeln('\x1b[36mYou can now type commands. The AI assistant is available with "ai help"\x1b[0m');
                    terminal.writeln('\x1b[33mWaiting for server prompt...\x1b[0m');
                    
                    // Ensure terminal is focused and ready for input
                    setTimeout(() => {
                        terminal.focus();
                        console.log(`SSH terminal focused and ready for input`);
                        console.log(`Current connection set to: ${currentConnectionId}`);
                        console.log(`Session ID match: ${currentConnectionId === data.session_id}`);
                    }, 300);
                    
                } else {
                    updateStatus(`Failed to connect to ${connection.hostname}: ${data.message}`);
                }
            } else {
                console.error(`Could not find connection for session_id: ${data.session_id}`);
            }
        }
        
        function handleSSHError(data) {
            const connection = activeConnections.get(data.session_id);
            if (connection) {
                connection.status = 'disconnected';
                
                const statusElement = connection.element.querySelector('.connection-status');
                statusElement.textContent = 'Error';
                statusElement.className = 'connection-status status-disconnected';
                
                updateStatus(`SSH Error: ${data.error}`);
                
                // Show error in terminal
                terminal.writeln(`\r\n\x1b[31mSSH Connection Error: ${data.error}\x1b[0m`);
                terminal.writeln('\x1b[33mPlease check your connection details and try again.\x1b[0m\r\n');
            }
        }
        
        function handleSSHDisconnected(data) {
            const connection = activeConnections.get(data.session_id);
            if (connection) {
                connection.status = 'disconnected';
                
                const statusElement = connection.element.querySelector('.connection-status');
                statusElement.textContent = 'Disconnected';
                statusElement.className = 'connection-status status-disconnected';
                
                updateStatus(`Disconnected from ${connection.hostname}`);
                
                // Show disconnection message in terminal
                terminal.writeln(`\r\n\x1b[33mSSH connection lost to ${connection.hostname}\x1b[0m`);
            }
        }
        
        function handleAICommandResponse(data) {
            // Display AI generated command
            terminal.writeln(`\x1b[36m🤖 AI Generated Command:\x1b[0m`);
            terminal.writeln(`\x1b[32m${data.command}\x1b[0m`);
            
            if (data.suggestions && data.suggestions.length > 0) {
                terminal.writeln(`\x1b[36m💡 Related suggestions:\x1b[0m`);
                data.suggestions.forEach(suggestion => {
                    terminal.writeln(`  • ${suggestion}`);
                });
            }
            terminal.writeln('');
            
            // Add to AI chat
            addAIMessage(`User: ${data.query}`, 'user');
            addAIMessage(`AI: Generated command: ${data.command}`, 'ai');
        }
        
        function handleAIChatStreamStart(data) {
            // Add user message to chat
            addAIMessage(`User: ${data.message}`, 'user');
            
            // Create a placeholder for the streaming AI response
            const aiContent = document.getElementById('aiContent');
            const streamDiv = document.createElement('div');
            streamDiv.style.margin = '4px 0';
            streamDiv.style.color = '#6c9bd1';
            streamDiv.id = 'ai-streaming-response';
            streamDiv.textContent = 'AI: ';
            aiContent.appendChild(streamDiv);
            aiContent.scrollTop = aiContent.scrollHeight;
        }
        
        function handleAIChatStreamChunk(data) {
            // Append chunk to the streaming response
            const streamDiv = document.getElementById('ai-streaming-response');
            if (streamDiv) {
                streamDiv.textContent = `AI: ${data.partial_response}`;
                const aiContent = document.getElementById('aiContent');
                aiContent.scrollTop = aiContent.scrollHeight;
            }
        }
        
        function handleAIChatResponse(data) {
            // Remove streaming placeholder and add final response
            const streamDiv = document.getElementById('ai-streaming-response');
            if (streamDiv) {
                streamDiv.remove();
            }
            
            // Add final complete response (only if we don't already have user message from streaming)
            const aiContent = document.getElementById('aiContent');
            const lastMessage = aiContent.lastElementChild;
            const hasUserMessage = lastMessage && lastMessage.textContent.startsWith(`User: ${data.message}`);
            
            if (!hasUserMessage) {
                addAIMessage(`User: ${data.message}`, 'user');
            }
            addAIMessage(`AI: ${data.response}`, 'ai');
        }
        
        function handleSuggestionsResponse(data) {
            // Update suggestions panel
            const suggestions = document.getElementById('suggestions');
            const items = suggestions.querySelectorAll('.suggestion-item');
            
            // Clear existing suggestions
            items.forEach(item => item.remove());
            
            if (data.suggestions && data.suggestions.length > 0) {
                data.suggestions.forEach(suggestion => {
                    const item = document.createElement('div');
                    item.className = 'suggestion-item';
                    item.textContent = suggestion.text || suggestion.command;
                    item.onclick = () => applySuggestion(item);
                    suggestions.appendChild(item);
                });
                
                suggestions.classList.add('show');
                setTimeout(() => {
                    suggestions.classList.remove('show');
                }, 5000);
            }
        }
        
        function handleAIError(data) {
            console.error('AI Error:', data.error);
            addAIMessage(`AI Error: ${data.error}`, 'ai');
            terminal.writeln(`\x1b[31m🤖 AI Error: ${data.error}\x1b[0m`);
        }

        function reconnectSSH(connectionId) {
            const connection = activeConnections.get(connectionId);
            if (connection) {
                connection.status = 'connecting';
                
                const statusElement = connection.element.querySelector('.connection-status');
                statusElement.textContent = 'Connecting...';
                statusElement.className = 'connection-status status-connecting';
                
                connectSSH(connectionId, connection);
            }
        }

        function removeConnection(connectionId) {
            if (confirm('Are you sure you want to remove this connection?')) {
                const connection = activeConnections.get(connectionId);
                if (connection) {
                    // Remove from UI
                    connection.element.remove();
                    
                    // Disconnect if active
                    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                        webSocket.send(JSON.stringify({
                            type: 'ssh_disconnect',
                            session_id: connectionId
                        }));
                    }
                    
                    // Remove from active connections
                    activeConnections.delete(connectionId);
                    
                    // Switch to local if this was the active connection
                    if (currentConnectionId === connectionId) {
                        selectConnection('local');
                    }
                }
            }
        }

        function newConnection() {
            showSSHModal();
        }

        function selectConnection(connectionId) {
            // Update UI
            document.querySelectorAll('.connection-item').forEach(item => {
                item.classList.remove('active');
            });
            
            const connectionElement = document.querySelector(`[data-connection-id="${connectionId}"]`);
            if (connectionElement) {
                connectionElement.classList.add('active');
            }
            
            // Update current connection
            const previousConnectionId = currentConnectionId;
            currentConnectionId = connectionId;
            
            // Clear command buffer when switching connections
            currentCommand = '';
            
            console.log(`Switching connection from ${previousConnectionId} to ${connectionId}`);
            
            // Update status
            if (connectionId === 'local') {
                updateStatus('Local Terminal Active');
            } else {
                const connection = activeConnections.get(connectionId);
                if (connection) {
                    updateStatus(`Connected to ${connection.hostname} (${connection.status})`);
                }
            }
            
            // Clear terminal and show appropriate content
            if (previousConnectionId !== connectionId) {
                terminal.clear();
                
                if (connectionId === 'local') {
                    terminal.writeln('\x1b[32mLocal Terminal Active\x1b[0m');
                    terminal.writeln('\x1b[36mType "ai help" for AI assistant commands\x1b[0m');
                    terminal.writeln('');
                    showPrompt();
                } else {
                    const connection = activeConnections.get(connectionId);
                    if (connection && connection.status === 'connected') {
                        terminal.writeln(`\x1b[32mSSH Session: ${connection.hostname}\x1b[0m`);
                        terminal.writeln('\x1b[36mConnected to remote server - AI assistant available with "ai help"\x1b[0m');
                        terminal.writeln('');
                        // SSH server will provide its own prompt
                    } else {
                        terminal.writeln(`\x1b[31mConnection to ${connection ? connection.hostname : 'unknown'} not active\x1b[0m`);
                        terminal.writeln('\x1b[33mPlease reconnect to use this session\x1b[0m');
                    }
                }
                
                // Ensure terminal is focused after switching
                setTimeout(() => {
                    terminal.focus();
                    console.log(`Terminal focused for connection: ${connectionId}`);
                }, 100);
            }
        }

        function toggleAI() {
            aiAssistantEnabled = !aiAssistantEnabled;
            const panel = document.getElementById('aiPanel');
            panel.style.display = aiAssistantEnabled ? 'flex' : 'none';
            updateStatus(aiAssistantEnabled ? 'AI Assistant Enabled' : 'AI Assistant Disabled');
        }

        function openSettings() {
            alert('Settings panel would open here in a full implementation');
        }

        function newTab() {
            const tabs = document.querySelector('.terminal-tabs');
            const tabCount = tabs.querySelectorAll('.terminal-tab').length;
            
            const newTab = document.createElement('div');
            newTab.className = 'terminal-tab';
            newTab.innerHTML = `
                <span>Terminal ${tabCount}</span>
                <button class="close-btn" onclick="closeTab(this)">&times;</button>
            `;
            
            // Remove active class from all tabs
            tabs.querySelectorAll('.terminal-tab').forEach(tab => tab.classList.remove('active'));
            newTab.classList.add('active');
            
            tabs.insertBefore(newTab, tabs.lastElementChild);
        }

        function closeTab(button) {
            const tab = button.closest('.terminal-tab');
            const tabs = tab.parentElement;
            
            if (tabs.querySelectorAll('.terminal-tab').length > 1) {
                tab.remove();
                
                // Activate first remaining tab if current was active
                if (tab.classList.contains('active')) {
                    const firstTab = tabs.querySelector('.terminal-tab');
                    if (firstTab) firstTab.classList.add('active');
                }
            }
        }

        function closeCurrentTab() {
            const activeTab = document.querySelector('.terminal-tab.active');
            if (activeTab) {
                const closeBtn = activeTab.querySelector('.close-btn');
                if (closeBtn) closeBtn.click();
            }
        }

        function updateStatus(message) {
            document.getElementById('statusLeft').textContent = message;
        }

        // Initialize the application when page loads
        document.addEventListener('DOMContentLoaded', initApp);
        
        // Close modal when clicking outside of it
        window.onclick = function(event) {
            const modal = document.getElementById('sshModal');
            if (event.target === modal) {
                closeSSHModal();
            }
        };
        
        // Add global keyboard shortcuts
        document.addEventListener('keydown', function(event) {
            // Ctrl+V or Cmd+V in SSH modal to auto-parse
            if ((event.ctrlKey || event.metaKey) && event.key === 'v') {
                const modal = document.getElementById('sshModal');
                if (modal.style.display === 'block') {
                    // Small delay to let the paste happen first
                    setTimeout(() => {
                        const activeElement = document.activeElement;
                        if (activeElement && activeElement.tagName === 'INPUT') {
                            // Try to parse if pasted into hostname field
                            if (activeElement.id === 'hostname') {
                                setTimeout(() => {
                                    const pastedValue = activeElement.value;
                                    if (pastedValue) {
                                        const parsed = parseConnectionString(pastedValue);
                                        if (parsed && (parsed.username || parsed.port !== 22)) {
                                            // Only auto-fill if we got more than just hostname
                                            if (parsed.port !== 22) document.getElementById('port').value = parsed.port;
                                            if (parsed.username) document.getElementById('username').value = parsed.username;
                                            if (parsed.password) document.getElementById('password').value = parsed.password;
                                            // Clean up hostname field to just show hostname
                                            activeElement.value = parsed.hostname;
                                            showPasteSuccess(parsed);
                                        }
                                    }
                                }, 10);
                            }
                        }
                    }, 10);
                }
            }
            
            // ESC to close modal
            if (event.key === 'Escape') {
                const modal = document.getElementById('sshModal');
                if (modal.style.display === 'block') {
                    closeSSHModal();
                }
            }
        });
    </script>
</body>
</html>